package com.utils.basehelper.encrypt;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

public class Base64Util {

	private static final String UTF_8 = "UTF-8";

	/**
	 * 对给定的字符串进行base64解码操作
	 */
	public static String decode(String inputData) {
		try {
			if (null == inputData) {
				return null;
			}
			return new String(Base64.decodeBase64(inputData.getBytes(UTF_8)), UTF_8);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 对给定的字符串进行base64加密操作
	 */
	public static String encode(String inputData) {
		try {
			if (null == inputData) {
				return null;
			}
			return new String(Base64.encodeBase64(inputData.getBytes(UTF_8)), UTF_8);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 将图片url转化成base64
	 * @param imgFile
	 * @return
	 */
	public static String getImgStr(String imgFile) {
		ByteArrayOutputStream data = new ByteArrayOutputStream();
		try {
			// 创建URL
			URL url = new URL(imgFile);
			// 创建链接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5000);
			InputStream is = conn.getInputStream();
			// 将内容放到内存中
			byte[] by = new byte[1024];
			int len = -1;
			while ((len = is.read(by)) != -1) {
				data.write(by, 0, len);
			}
			is.close();
			// 对字节数组Base64编码
			return Base64.encodeBase64String(data.toByteArray());
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String urlToBase64(String urlStr) {
		if (StringUtils.isBlank(urlStr)) {
			return null;
		}
		// 创建一个URL对象
		URL url = null;
		try {
			url = new URL(urlStr);
			byte[] urlBytes = IOUtils.toByteArray(url.openStream());
			return java.util.Base64.getEncoder().encodeToString(urlBytes);
		} catch (MalformedURLException e) {
//			log.info("Invalid URL:{}, e:{}", urlStr, e);
			return null;
		} catch (IOException e) {
//			log.info("Get URL InputStream Failed:{}, e:{}", urlStr, e);
			return null;
		}
	}

}
